package me.idashu.attg.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import me.idashu.attg.domain.ContributionEntity;
import me.idashu.attg.domain.GroupEntity;
import me.idashu.attg.domain.PageEntity;
import me.idashu.attg.domain.RecommendsDataStatisticsEntity;
import me.idashu.attg.domain.RoleEntity;
import me.idashu.attg.domain.UserEntity;
import me.idashu.attg.service.UserService;
import me.idashu.attg.service.UserrecommService;
import me.idashu.attg.util.Escape;
import me.idashu.attg.util.SystemConfig;
import me.idashu.attg.util.WeekDay;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/user")
public class UserController {
	
	private SystemConfig systemConfig;
	
	@Autowired
	private UserrecommService userrecommService;

	@Autowired
	private UserService userService;
	
	/**
	 * 查询用户列表
	 * 
	 * @param pageEntity
	 * @param userEntity
	 * @param model
	 * @return
	 */
	/**
	 * 查询用户列表公共的方法
	 * @param pageEntity
	 * @param userEntity
	 * @param request
	 * @param model
	 */

	@RequestMapping(value = "/web/memberList")
	public String preMemberList(@ModelAttribute PageEntity pageEntity,
			Model model) {
		model.addAttribute("memberList", "用户列表");
		return "user_list";
	}

	@RequestMapping(value = "/web/adduser")
	public String preAddUser(Locale locale, Model model) {
		model.addAttribute("adduser", "添加用户");
		return "add_admin";
	}

	/**
	 * 验证页面输入的用户名是否存在
	 * 
	 * @param userName
	 * @param response
	 */
//	@RequestMapping(value = "/web/checkUserName")
//	public void preCheckUserName(@RequestParam("username") String userName,
//			HttpServletResponse response) {
//		response.setContentType("text/html;charset=GBK");
//		try {
//			String checkResult = null;
//			userName = Escape.unescape(userName);
//			int count = userService.getCountByUserName(userName);
//			if (count > 0) {
//				checkResult = "1";
//			} else {
//				checkResult = "0";
//			}
//			response.getWriter().print(checkResult);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

	@RequestMapping(value = "/web/login")
	public String preLogin(Locale locale, Model model) {
		return "user/login";
	}


	/**
	 * 
	 * @param locale
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/json/list", method = RequestMethod.POST)
	public @ResponseBody
	List<UserEntity> list(Locale locale, Model model) {

		List<UserEntity> shops = userService.getAllShop();
		// System.out.println(shops);
		// model.addAttribute("shops",shops);
		return shops;
	}


	@RequestMapping(value = "/web/left", method = RequestMethod.GET)
	public String left(Locale locale, Model model) {

		return "left";
	}

	@RequestMapping(value = "/web/breadcrumb", method = RequestMethod.GET)
	public String breadcrumb(Locale locale, Model model) {

		return "breadcrumb";
	}

	@RequestMapping(value = "/web/main", method = RequestMethod.GET)
	public String mains(Locale locale, Model model) {

		return "main";
	}
	
	@RequestMapping("/userLevelList")
	public String userLevelList(Model model){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userService.userLevelCount();
		PageEntity pageEntity = new PageEntity();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<RoleEntity> userLevelList = userService.userLevelList(map);
		if(userLevelList.size()<=0){
			userLevelList = null;
		}
		model.addAttribute("listUserLevel", "用户级别列表");
    	model.addAttribute("userLevelList", userLevelList);
    	model.addAttribute("pageEntity", pageEntity);
		return "userLevel_list";
	}
	
	@RequestMapping("/userLevelAjaxList")
	public String userLevelAjaxList(Model model,@ModelAttribute PageEntity pageEntity){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userService.userLevelCount();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<RoleEntity> userLevelList = userService.userLevelList(map);
		model.addAttribute("listUserLevel", "用户级别列表");
    	model.addAttribute("userLevelList", userLevelList);
    	model.addAttribute("pageEntity", pageEntity);
		return "userLevel_list";
	}
	
	@RequestMapping("/deleteUserLevel")
	public String deleteUserLevel(@RequestParam("roleId") int roleId,Model model){
		userService.deleteUserLevel(roleId);
		userLevelList(model);
		return  "userLevel_list";
	}
	
	@RequestMapping("/addUserLevel")
	public String addUserLevel(Model model){
		List<GroupEntity> listGroup = userService.getAllGroup();
		model.addAttribute("addLevel", "添加用户级别");
		model.addAttribute("listGroup", listGroup);
		return "add_userLevel";
	}
	
	
	@RequestMapping("/addUserLevelInfo")
	public String addUserLevelInfo(Model model,@ModelAttribute RoleEntity roleEntity){
		String rolename = roleEntity.getRolename();
		int count = userService.getCountByRoleName(rolename);
		if(count>0){
			model.addAttribute("success", "该级别已存在，请重新添加！");
			return "gonggao";
		}else{
			model.addAttribute("success", "添加级别成功！");
			roleEntity.setTime(new Date());
			userService.addUserLevelInfo(roleEntity);
		}
		return "success";
	}
	
	@RequestMapping("/updateRole")
	public String updateRole(Model model,@RequestParam("roleId") int roleId){
		List<GroupEntity> listGroup = userService.getAllGroup();
		RoleEntity roleEntity = userService.getRole(roleId);
		model.addAttribute("updateRole", "修改用户级别");
		model.addAttribute("listGroup", listGroup);
		model.addAttribute("roleEntity", roleEntity);
		return "update_userLevel";
	}
	
	@RequestMapping("/updateUserLevelInfo")
	public String updateUserLevelInfo(Model model,@ModelAttribute RoleEntity roleEntity){
		String rolename = roleEntity.getRolename();
		model.addAttribute("success", "修改级别成功！");
		roleEntity.setTime(new Date());
		userService.updateUserLevelInfo(roleEntity);
		return "success";
	}
	
	@RequestMapping("/userList")
	public String userList(Model model){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userService.userCount();
		PageEntity pageEntity = new PageEntity();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<UserEntity> listUser = userService.userList(map);
		if(listUser.size()<=0){
			listUser = null;
		}
		model.addAttribute("userList", "用户列表");
    	model.addAttribute("listUser", listUser);
    	model.addAttribute("pageEntity", pageEntity);
		return "user_list";
	}
	
	@RequestMapping("/userAjaxList")
	public String userAjaxList(Model model,@ModelAttribute PageEntity pageEntity){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userService.userCount();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		List<UserEntity> listUser = userService.userList(map);
		if(listUser.size()<=0){
			listUser = null;
		}
		model.addAttribute("userList", "用户列表");
    	model.addAttribute("listUser", listUser);
    	model.addAttribute("pageEntity", pageEntity);
		return "user_list";
	}
	
	@RequestMapping("/forbiddenUser")
	public String forbiddenUser(@RequestParam("user_id") int user_id,Model model){
		try {
			userService.forbiddenUser(user_id);
			userList(model);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user_list";
	}
	
	@RequestMapping("/userPartExport")
	public void userPartExport(@RequestParam("dateFrom") String dateFrom,@RequestParam("dateTo") String dateTo,HttpServletResponse response){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			dateFrom = dateFrom+" 00:00:00";
			dateTo = dateTo+" 23:59:59";
			map.put("dateFrom", dateFrom);
			map.put("dateTo", dateTo);
			List<UserEntity> listUser = userService.userList(map);
			String xlsPath = systemConfig.getDir("xlsPath");
//			String xlsPath = "E:/用户数据统计.xls";
			toXLS(listUser, xlsPath);
			downloadFile(new File(xlsPath),"result.xls",response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/userExport")
	public void userExport(HttpServletResponse response){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dateFrom", "");
			map.put("dateTo", "");
			List<UserEntity> listUser = userService.userList(map);
			String xlsPath = systemConfig.getDir("xlsPath");
//			String xlsPath = "E:/用户数据统计.xls";
			toXLS(listUser, xlsPath);
			downloadFile(new File(xlsPath),"result.xls",response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void toXLS(Collection collection,String path) {   
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			WritableWorkbook book = Workbook.createWorkbook(new File(path));
			WritableSheet sheet = book.createSheet("导出数据", 0);
			Label labe1 = new Label(0, 0, "用户名");
			Label labe2 = new Label(1, 0, "注册时间");
			Label labe3 = new Label(2, 0, "性别");
			Label labe4 = new Label(3, 0, "年龄");
			Label labe5 = new Label(4, 0, "注册地区");
			Label labe6 = new Label(5, 0, "坐标地区");
			Label labe7 = new Label(6, 0, "发言总量");
			Label labe8 = new Label(7, 0, "今日发言次数");
			Label labe9 = new Label(8, 0, "今日评论总量");
			Label labe10 = new Label(9, 0, "参与内容的总量");
			Label labe11 = new Label(10, 0, "被投诉次数");
//			Label labe12 = new Label(11, 0, "客户端");
			
			sheet.addCell(labe1);
			sheet.addCell(labe2);
			sheet.addCell(labe3);
			sheet.addCell(labe4);
			sheet.addCell(labe5);
			sheet.addCell(labe6);
			sheet.addCell(labe7);
			sheet.addCell(labe8);
			sheet.addCell(labe9);
			sheet.addCell(labe10);
			sheet.addCell(labe11);
//			sheet.addCell(labe12);
			
			Iterator it = collection.iterator();
			int i = 1;
			while(it.hasNext()) {
				UserEntity srrf = (UserEntity) it.next();
				Label label1 = new Label(0, i, srrf.getUsername());
				Label label2 = new Label(1, i, sdf.format(srrf.getTime()));
				Label label3 = new Label(2, i, srrf.getSex());
				Label label4 = new Label(3, i, String.valueOf(srrf.getAge()));
				Label label5 = new Label(4, i, srrf.getCityname());
				Label label6 = new Label(5, i, srrf.getAddress1());
				Label label7 = new Label(6, i, String.valueOf(srrf.getNotecount()));
				Label label8 = new Label(7, i, String.valueOf(srrf.getNotedaycount()));
				Label label9 = new Label(8, i, String.valueOf(srrf.getCommentdaycount()));
				Label label10 = new Label(9, i, String.valueOf(srrf.getContextcount()));
				Label label11 = new Label(10, i, String.valueOf(srrf.getTipcount()));
//				Label label12 = new Label(11, i, srrf.get);
				
				sheet.addCell(label1);
				sheet.addCell(label2);
				sheet.addCell(label3);
				sheet.addCell(label4);
				sheet.addCell(label5);
				sheet.addCell(label6);
				sheet.addCell(label7);
				sheet.addCell(label8);
				sheet.addCell(label9);
				sheet.addCell(label10);
				sheet.addCell(label11);
				i++;
			}
			book.write();
			book.close();
		} catch (Exception e) {    
			
			e.printStackTrace();    
		}
	}
	
	protected void downloadFile(File file,String fileName,
			HttpServletResponse response) throws Exception {
		response.setContentType("application/oct-stream;charset=UTF-8");
		response.setHeader("Content-disposition",
				"attachment;filename="+fileName);
		BufferedInputStream in = new BufferedInputStream(new
				FileInputStream(file));
		BufferedOutputStream out = new BufferedOutputStream(response.
				getOutputStream());
		byte[] buff = new byte[4096];
		int length = -1;
		while ((length = in.read(buff)) != -1) {
			out.write(buff, 0, length);
		}
		in.close();
		out.close();
	}
	
	
	@RequestMapping("/partUserList")
	public String partUserList(Model model,@RequestParam("recommendId") int recommendId){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userrecommService.recommendCount(recommendId);
		PageEntity pageEntity = new PageEntity();
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		map.put("recommendId", recommendId);
		List<UserEntity> listUser = userService.partUserList(map);
		if(listUser.size()<=0){
			listUser = null;
		}
    	model.addAttribute("listUser", listUser);
    	model.addAttribute("recommendId", recommendId);
    	model.addAttribute("pageEntity", pageEntity);
    	return "userAjaxList";
	}
	
	@RequestMapping("/partUserAjaxList")
	public String partUserAjaxList(Model model,@ModelAttribute PageEntity pageEntity,@RequestParam("recommendId") int recommendId){
		Map<String, Object> map = new HashMap<String, Object>();
		int total = userrecommService.recommendCount(recommendId);
		pageEntity.setTotalPage(total);
		pageEntity.setPageLess(pageEntity.getPage());
		map.put("pageEntity", pageEntity);
		map.put("recommendId", recommendId);
		List<UserEntity> listUser = userService.partUserList(map);
		if(listUser.size()<=0){
			listUser = null;
		}
    	model.addAttribute("listUser", listUser);
    	model.addAttribute("recommendId", recommendId);
    	model.addAttribute("pageEntity", pageEntity);
    	return "userAjaxList";
	}
}
